/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.server.db.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Target;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Czarek
 */
public class FileUtils {

    private static final Logger log = Logger.getLogger(FileUtils.class.getName());
    private static final int BUF_SIZE = 512;

    
    private final File target;
    private FileUtils() {
        this(new File("./"));
    }
    
    public FileUtils(File target){
        this.target = target;
        if(!target.exists()){
            target.mkdirs();
        }
    }
    
    
    
    private String extracted;

    public static FileUtils getInstance() {
        return new FileUtils();
    }

    public void setExtract(final String file) {
        extractFile(file);
        extracted = new File(target,file).getPath();
    }

    public String getExtract() {
        return extracted;
    }

    public void extractFile(final String file) {
        InputStream is = FileUtils.class.getClassLoader().getResourceAsStream(file);
        if(is==null){
            log.log(Level.SEVERE,"Resource {0} is not found on classpath", file);
            throw new IllegalStateException(String.format("Resource %s is was not found on classpath", file));
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(new File(target,file));
            final byte[] buffer = new byte[BUF_SIZE];
            int read;
            while ((read = is.read(buffer)) > 0) {
                os.write(buffer, 0, read);
            }
        } catch (FileNotFoundException ex) {
            log.log(Level.SEVERE, "File not found", ex);
        } catch (IOException ex) {
            log.log(Level.SEVERE, "IO error", ex);
        } finally {
            try {
                is.close();
                if (os != null) {
                    os.close();
                }
            } catch (IOException ex) {
                log.log(Level.SEVERE, "Error while closing file", ex);
            }
        }
    }
}
